import { from } from './entity'

export function createWhere (predicate) {
  return (data) => {
    return data.filter(predicate)
  }
}

export function createOrder (predicate) {
  return (data) => {
    return data.sort(predicate)
  }
}

export function createPartial (limit, offset) {
  return (data) => {
    return data.slice(offset * limit, (offset + 1) * limit)
  }
}

export function createMap (predicate) {
  return (data) => {
    return data.map(predicate)
  }
}

export function createGroup (predicate) {
  return (data) => {
    const set = new Set()
    const result = []
    data.forEach(item => {
      const key = predicate(item)
      if (set.has(key)) {
        const group = result.find(groupItem => groupItem.value === key)
        group.items.push(item)
      } else {
        const group = {
          value: key,
          items: [item]
        }
        set.add(key)
        result.push(group)
      }
    })
    return result
  }
}

export function runPipeline (data, pipeline) {
  return from(data)
    .setPipeline(pipeline)
    .value()
}

export function runPipelineCount (data, pipeline) {
  return from(data)
    .setPipeline(pipeline)
    .count()
}

export function runPipelineUpdate (data, pipeline, predicate, key = 'id') {
  return from(data)
    .setPipeline(pipeline)
    .update(predicate, key)
}

export function runPipelineDelete (data, pipeline, key = 'id') {
  return from(data)
    .setPipeline(pipeline)
    .delete(key)
}
